package org.mat.admin.sys.controller;


import org.mat.admin.sys.domain.SysMenu;
import org.mat.admin.sys.domain.vo.RouterVo;
import org.mat.admin.sys.service.ISysMenuService;
import org.mat.admin.sys.util.SecurityConstants;
import org.mat.admin.sys.util.SecurityUtils;
import org.mat.admin.sys.util.StringUtils;
import org.mat.framework.core.context.RequestContext;
import org.mat.framework.core.context.RequestContextUtils;
import org.mat.framework.lang.constant.DefaultErrors;
import org.mat.framework.lang.dto.MatApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */

    @GetMapping("/list")
    public MatApiResponse list(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return MatApiResponse.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */

    @GetMapping(value = "/{menuId}")
    public MatApiResponse getInfo(@PathVariable Long menuId) {
        return MatApiResponse.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public MatApiResponse treeselect(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return MatApiResponse.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public MatApiResponse roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        HashMap<String, Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        MatApiResponse ret = MatApiResponse.success(ajax);
        return ret;
    }

    /**
     * 新增菜单
     */

    @PostMapping
    public MatApiResponse add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */

    @PutMapping
    public MatApiResponse edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */

    @DeleteMapping("/{menuId}")
    public MatApiResponse remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return MatApiResponse.fail(DefaultErrors.DEFAULT.getCode(), "菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public MatApiResponse getRouters() {
        RequestContext requestContext = RequestContextUtils.get();
        Map<String, String> requestContextData = requestContext.getData();
        String userIdRC = requestContextData.get(SecurityConstants.DETAILS_USER_ID);


        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(Long.valueOf(userIdRC));
        List<RouterVo> data = menuService.buildMenus(menus);
        return MatApiResponse.success(data);
    }
}